using _RobotInspection.DTO;
using _RobotInspection.Services;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using MQTTnet;
using MQTTnet.Client;
using SqlSugar;
using System.Text.Json;

namespace _RobotInspection.Services
{
    /// <summary>
    /// MQTT服务类
    /// </summary>
    public class MqttService
    {
        private readonly IMqttClient _mqttClient;
        private readonly IConfiguration _configuration;
        private readonly ILogger<MqttService> _logger;
        private readonly WebSocketService _webSocketService;
        private readonly ISqlSugarClient _db;

        // 添加新字段存储 WebSocket 接收到的筛选条件
        private string _selectedUnit;
        private string _selectedEquipment;


        /// <summary>
        /// 添加筛选条件模型
        /// </summary>
        public class FilterCondition
        {
            public string Unit { get; set; }
            public string EquipmentName { get; set; }
        }

        /// <summary>
        /// 处理 WebSocket 消息
        /// </summary>
        /// <param name="message"></param>
        /// <returns></returns>
        private Task HandleWebSocketMessage(string message)
        {
            try
            {
                var filterCondition = System.Text.Json.JsonSerializer.Deserialize<FilterCondition>(message);
                _selectedUnit = filterCondition.Unit;
                _selectedEquipment = filterCondition.EquipmentName;
                Console.WriteLine($"收到WebSocket消息: {message}");

            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "处理WebSocket控制消息时出错");
            }
            return Task.CompletedTask;
        }

        public MqttService(IConfiguration configuration, ILogger<MqttService> logger, WebSocketService webSocketService, ISqlSugarClient db)
        {
            _configuration = configuration;
            _logger = logger;
            var factory = new MqttFactory();
            _mqttClient = factory.CreateMqttClient();
            _webSocketService = webSocketService;
            _db = db;
            // 订阅 WebSocket 消息
            _webSocketService.MessageReceived += HandleWebSocketMessage;
        }

        public async Task StartAsync()
        {
            var options = new MqttClientOptionsBuilder()
                .WithTcpServer(_configuration["Mqtt:Host"], int.Parse(_configuration["Mqtt:Port"]))
                // .WithCredentials(_configuration["Mqtt:Username"], _configuration["Mqtt:Password"])
                // .WithClientId(_configuration["Mqtt:ClientId"])
                .Build();

            _mqttClient.ApplicationMessageReceivedAsync += HandleMessageAsync;

            await _mqttClient.ConnectAsync(options);

            // 订阅主题
            var topicFilter = new MqttTopicFilterBuilder()
                .WithTopic(_configuration["Mqtt:Topic"])
                .Build();
            await _mqttClient.SubscribeAsync(topicFilter);
        }


        /// <summary>
        /// 处理 MQTT 消息
        /// </summary>
        /// <param name="e"></param>
        /// <returns></returns>
        private async Task HandleMessageAsync(MqttApplicationMessageReceivedEventArgs e)
        {
            try
            {
                var payload = System.Text.Encoding.UTF8.GetString(e.ApplicationMessage.Payload);
                // Console.WriteLine($"收到消息: Topic = {e.ApplicationMessage.Topic}, Payload = {payload}");



            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "处理MQTT消息时出错");
                Console.WriteLine(ex.Message);
            }


            //return  Task.CompletedTask;
        }
    }
}
